<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Weixin {

	protected $_ci;
	protected $_token = '';
	protected $_appid = '';
	protected $_appsecret = '';

	protected $_event = array();

	public function __construct(){
		$this->_ci = & get_instance();
		$this->_ci->load->library('rest');
	}

	public function init($token,$appid,$appsecret){
		$this->_token = $token;
		$this->_appid = $appid;
		$this->_appsecret = $appsecret;
	}

	public function checkSignature($signature,$nonce,$timestamp){
		$arr = array($this->_token,$timestamp,$nonce);
		sort($arr);
		$arr = implode($arr);
		$arr = sha1($arr);

		return ($arr == $signature);
	}

	public function catchEvent(){
		$input = id2name('HTTP_RAW_POST_DATA',$GLOBALS);
		if(!validate($input)) return array();

		xml_parse_into_struct(xml_parser_create(),$input,$data);

		$info = array();
		foreach($data as $record){
			if($record['tag'] == 'TOUSERNAME') $info['tousername'] = $record['value'];
			elseif($record['tag'] == 'FROMUSERNAME') $info['fromusername'] = $record['value'];
			elseif($record['tag'] == 'CREATETIME') $info['createtime'] = $record['value'];
			elseif($record['tag'] == 'MSGTYPE') $info['msgtype'] = $record['value'];
			elseif($record['tag'] == 'EVENT') $info['event'] = $record['value'];
			elseif($record['tag'] == 'EVENTKEY') $info['eventkey'] = $record['value'];
			elseif($record['tag'] == 'CONTENT') $info['Content'] = $record['value'];
		}

		$this->_event = $info;
		return !empty($info);
	}

	public function generateTextResponse($content){
		$to = $this->_event['fromusername'];
		$from = $this->_event['tousername'];
		$textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
					</xml>";
		$resultStr = sprintf($textTpl,$to,$from,time(),'text',$content);

		echo $resultStr;
		die();
	}

	public function generateNewsResponse($list){
		$to = $this->_event['fromusername'];
		$from = $this->_event['tousername'];
		$textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<ArticleCount>%s</ArticleCount>
					<Articles>";
		$resultStr = sprintf($textTpl,$to,$from,time(),'news',count($list));

		$textTpl = "<item>
				<Title><![CDATA[%s]]></Title>
				<Description><![CDATA[%s]]></Description>
				<PicUrl><![CDATA[%s]]></PicUrl>
				<Url><![CDATA[%s]]></Url>
				</item>";
		foreach($list as $record){
			$item = sprintf($textTpl,$record['title'],$record['desc'],$record['image'],$record['url']);
			$resultStr .= $item;
		}

		$resultStr .= '</Articles></xml>';

		echo $resultStr;
		die();
	}

	public function updateMenu($menu){
		foreach($menu['button'] as $key => $record){
			$menu['button'][$key]['name'] = urlencode($record['name']);
			foreach($record['sub_button'] as $sub_key => $sub){
				$menu['button'][$key]['sub_button'][$sub_key]['name'] = urlencode($sub['name']);
			}
		}
		$menu = json_encode($menu);
		$menu = urldecode($menu);
		$access_token = $this->_fetchAccessToken();
		$this->_ci->rest->format('json');
		$res = $this->_ci->rest->post('https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token,$menu);
		show($res);
	}

	public function getFromUserName(){
		if(isset($this->_event['fromusername'])) return $this->_event['fromusername'];
		else return '';
	}

	public function getMessageContent(){
		if(isset($this->_event['Content'])) return $this->_event['Content'];
		else return '';
	}

	public function eventSubscribe(){
		if($this->_event['msgtype'] == 'event' && isset($this->_event['event']) && $this->_event['event'] == 'subscribe') return true;

		return false;
	}

	public function eventUnsubscribe(){
		if($this->_event['msgtype'] == 'event' && isset($this->_event['event']) && $this->_event['event'] == 'unsubscribe') return true;

		return false;
	}

	public function eventClick($key){
		if($this->_event['msgtype'] == 'event' && isset($this->_event['event']) && $this->_event['event'] == 'CLICK' && $this->_event['eventkey'] == $key) return true;

		return false;
	}

	public function message(){
		if($this->_event['msgtype'] == 'text') return true;

		return false;
	}

	protected function _fetchAccessToken(){
		$access_token = $this->_ci->rest->get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_appid.'&secret='.$this->_appsecret);
		$access_token = json_decode($access_token,true);
		$access_token = id2name('access_token',$access_token);

		return $access_token;
	}

	public function log($content){
		log_message('error',$content);
	}
}

/* End of file weixin.php */
/* Location: ./application/libraries/weixin.php */